<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 总包签证确认归档编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      class="updateControlPointHandover"
      :class="editModel == 0 ? 'disabledControlPointHandover' : ''"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="测量控制点移交"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''"
                       @selectOrg="selectOrg"
                       @getProjectInfo="getProjectInfo">
            <!-- 表格 -->
            <!-- ref="formTable"
                 tableLayout="fixed"
                 size="default"
                 rowKey="id"
                :columns="columns"
                :data="technicalConstructionSurveyControlPoints"
                :alert="true"
                :scroll="{ x: 500 }"
                :showPagination="false" -->
            <template v-slot:table>
              <a-form-model-item class="mb20" label=" " :colon="false">
                <a-table
                  ref="formTable"
                  bordered
                  :columns="columns"
                  :data-source="form.technicalConstructionSurveyControlPoints"
                  :pagination="false"
                >
                  <span slot="customTitle">照片(<span style="color: red">*必传</span>)</span>
                  <template
                    v-for="col in ['point', 'floor', 'x', 'y', 'fileInfoList']"
                    :slot="col"
                    slot-scope="text, record"
                  >
                    <div :key="col" class="form-item">
                      <template>
                        <template>
                          <BaseInput
                            v-if="col === 'point'"
                            v-model="record[col]"
                            :disabled="editModel == 0"
                          ></BaseInput>
                          <BaseInputNumber
                            v-else-if="col === 'floor' || col === 'x' || col === 'y'"
                            v-model="record[col]"
                            :disabled="editModel == 0"
                          >
                          </BaseInputNumber>
                          <UploadList
                            v-else-if="col === 'fileInfoList'"
                            businessCode="FACE13"
                            :disabled="editModel == 0"
                            uploadType="image"
                            :editModel="editModel"
                            multiple
                            :upload-arrys.sync="record[col]"
                          />
                        </template>
                      </template></div
                  ></template>
                  <template slot="action" slot-scope="text, record, index">
                    <span v-if="editModel != 0">
                      <a-popconfirm title="确定要删除?" @confirm="() => del(record, index)">
                        <a>删除</a>
                      </a-popconfirm>
                    </span>
                  </template>
                  <template v-if="editModel != 0" slot="footer">
                    <a-button type="primary" @click="addLine">添加行</a-button>
                  </template>
                </a-table>
              </a-form-model-item>
            </template>
            <!-- 附件上传 -->
            <template #fileInfoList>
              <template v-if="editModel != 0">
                <l-table businessCode="FACE12" :uploadArrys.sync="form.fileInfoList"></l-table>
              </template>
              <file-link v-else :fileList="form.fileInfoList" style="margin-top: -3px"></file-link>
            </template>
          </custom-form>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button
            class="button_right"
            v-if="form.status == 'REJECTED'"
            type="primary"
            :loading="loadingBtn.REJECTED"
            @click="handleSubmit('REJECTED')"
            >保存</a-button
          >
          <a-button
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED')"
            >提交</a-button
          >
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
        <div class="btn_box page-btn-right-top" v-else>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
     
  </base-breadcrumb>
</template>

<script>
import {
  addTransferConstructionSurveyControlPoint,
  updateTransferConstructionSurveyControlPoint,
  getTransferConstructionSurveyControlPointById
} from '@/api/technical/controlPointHandover' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' //参与人员
import { transferTypeData } from './model'
import UploadList from '@/components/UploadList'
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    align: 'center',
    customRender() {
      return arguments[2] + 1
    }
  },
  { title: '点位号', dataIndex: 'point', align: 'center', scopedSlots: { customRender: 'point' } },
  { title: '高程', dataIndex: 'floor', align: 'center', scopedSlots: { customRender: 'floor' }},
  { title: 'X', dataIndex: 'riskRate', align: 'center', scopedSlots: { customRender: 'x' } },
  { title: 'Y', dataIndex: 'planRiskFee', align: 'center', scopedSlots: { customRender: 'y' } },
  {
    dataIndex: 'fileInfoList',
    align: 'center',
    scopedSlots: { customRender: 'fileInfoList' },
    width: 400,
    slots: { title: 'customTitle' }
  },
  { title: '操作', dataIndex: 'action', width: '120px', align: 'center', scopedSlots: { customRender: 'action' } }
]

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany,
    SelectPersonByProject,
    UploadList
  },
  data() {
    return {
      columns,
      loading: false, // 加载控件
      visible: false, //人员选择控件
      handedType: false, //通过移交来判断字段隐藏
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        projectDeptId: void 0,
        technicalConstructionSurveyControlPoints: [
          {
            point: null,
            floor: null,
            x: null,
            y: null,
            fileInfoList: []
          }
        ],
        curId: '', projectId: "", branchCompanyId: ""
      },
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        transferUnit: [{ required: true, message: '请输入移交单位', trigger: 'blur' }],
        transferPerson: [{ required: true, message: '请输入移交人', trigger: 'blur' }],
        transferPersonIds: [{ required: true, message: '请输入选择移交人', trigger: 'change' }],
        recvUnit: [{ required: true, message: '请输入接收单位', trigger: 'blur' }],
        transferTime: [{ required: true, message: '请选择移交时间', trigger: 'change' }],
        participant: [{ required: true, message: '请选择参与人员', trigger: 'change' }],
        recvPerson: [{ required: true, message: '请输入接收人', trigger: 'blur' }],
        recvPersonIds: [{ required: true, message: '请选择接收人', trigger: 'change' }],
        transferType: [{ required: true, message: '请选择移交类型', trigger: 'change' }],
        buildingAndProjectLocation: [{ required: true, message: '请输入楼栋及工程部位', trigger: 'blur' }],
        participantNamesOut: [{ required: true, message: '请输入参加人员(外部)', trigger: 'blur' }],
        fileInfoList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }],
      }, // 校验规则
      init: false // 初始化控件
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileInfoList'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileInfoList')
        })
      }
    },
    //监听移交类型
    'form.transferType'(newVal) {
      this.handedType = newVal * 1 === 1 ? true : false
    }
  },
  async created() {},
  async mounted() {
    this.$route.meta.title = ['测量控制点移交 查看', '测量控制点移交 编辑', '测量控制点移交 新增'][this.editModel]
    await this.getDetailData()
  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'curId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: true
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '所属分公司',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   selectChange: (e) => {
        //     this.form.projectDeptId = e?.projectDeptId
        //   }
        // },
        {
          keyName: 'transferType',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '移交类型',
          data: transferTypeData
        },
        {
          keyName: 'transferUnit',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '移交单位',
          hidden: this.handedType
        },
        {
          type: SelectProject,
          keyName: 'transferUnitId',
          label: '移交单位',
          disabled: true,
          hidden: !this.handedType,
          attrs: {
            isDefaultSelected: this.editModel == 2,
            autoSelected: this.editModel == 2,
            keyValue: 'branchCompanyId',
            isClear: this.editModel == 2,
            isEdit: this.editModel != 2,
            form: this.form
          }
        },
        {
          keyName: 'transferPerson',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '移交人',
          hidden: this.handedType
        },
        {
          keyName: 'transferPersonIds',
          type: SelectPersonByProject,
          label: '移交人',
          placeholder: '搜索下拉，可多选',
          hidden: !this.handedType,
          disabled: this.editModel == 0,
          attrs: {
            isOrg: true,
            showSearch: true,
            orgId: this.form.projectDeptId,
            mode: 'multiple',
            optionLabelProp: 'children'
          }
        },
        {
          type: SelectProject,
          keyName: 'recvUnitId',
          label: '接收单位',
          disabled: true,
          hidden: this.handedType,
          attrs: {
            isDefaultSelected: this.editModel == 2,
            autoSelected: this.editModel == 2,
            keyValue: 'branchCompanyId',
            isClear: this.editModel == 2,
            isEdit: this.editModel != 2,
            form: this.form
          }
        },
        {
          keyName: 'recvUnit',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '接收单位',
          hidden: !this.handedType
        },
        {
          keyName: 'recvPerson',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '接收人',
          hidden: !this.handedType
        },
        {
          keyName: 'recvPersonIds',
          type: SelectPersonByProject,
          disabled: this.editModel == 0,
          label: '接收人',
          placeholder: '搜索下拉，可多选',
          hidden: this.handedType,
          attrs: {
            isOrg: true,
            showSearch: true,
            orgId: this.form.projectDeptId,
            mode: 'multiple',
            optionLabelProp: 'children'
          }
        },
        {
          keyName: 'transferTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '移交时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'buildingAndProjectLocation',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '楼栋及工程部位'
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        },
        {
          keyName: 'resultProducer',
          type: 'SelectPerson',
          isEcho:true,
          label: '参加人员(内部)',
          disabled: this.editModel == 0,
          personKeys: ['participantIds', 'participantNames'],
          span: 24,
        },
        // {
        //   keyName: 'resultProducer',
        //   type: 'SelectPerson',
        //   disabled: this.editModel == 0,
        //   label: '参加人员（内部)',
        //   personKeys: ['participantIds', 'participantNames'],
        //   list: this.form.resultProducer,
        //   // attrs: {
        //   //   list: this.form.resultProducer
        //   // },

        //   span: 24
        // },
        {
          keyName: 'participantNamesOut',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '参加人员(外部)',
          span: 24
        },
        {
          keyName: 'updateUserName',
          type: 'BaseInput',
          disabled: true,
          hidden: this.editModel * 1 === 2,
          label: '填报人'
        },
        {
          keyName: 'updateTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: true,
          label: '填报时间',
          hidden: this.editModel * 1 === 2,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          slot: true,
          keyName: 'fileInfoList',
          label: '附件上传',
          span: 24,
          businessCode: 'FACE12'
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      if(val.length&&val.length < 2) {
        this.form.branchCompanyId = val[val.length - 1].orgId
      } else if(val.length >= 2 ) {
        this.form.branchCompanyId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
      }
    },
    getProjectInfo(info) {
      this.$set(this.form, 'projectDeptId', info.projectDeptOrgId)
    },
    //添加行
    addLine() {
      this.form.technicalConstructionSurveyControlPoints.push({
        fileInfoList: [],
        floor: null,
        point: null,
        x: null,
        y: null
      })
      // this.$refs.formTable.refresh(true)
    },
    del(data, idx) {
      this.form.technicalConstructionSurveyControlPoints.splice(idx, 1)
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getTransferConstructionSurveyControlPointById({ id: this.id })
          .then((res) => {
            this.loading = false
            if (res.data.participant) {
              res.data.participant = res.data.participant.split(',')
            }
            this.form = { ...this.form, ...res.data }
            if(this.form.projectId) {
              this.form.curId =  this.form.projectId
            } else {
              this.form.curId =  this.form.branchCompanyId
            }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.form.curId = this.$userInfo().currentPost.id
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    /**
     * 提交表单
     */
    isEmpty(obj) {

      if ((typeof obj == 'undefined' || obj == null || obj == '' ) && obj!== 0) {
        return true
      } else {
        return false
      }
    },
    handleSubmit(status) {
      let dataDable = this.form.technicalConstructionSurveyControlPoints
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      if (!this.form.participantIds) {
        this.$message.warning('请添加参加人员（内部）')
        return
      }
      if (!dataDable.length) {
        this.$message.warning('请完善表格数据')
        return
      } else {
         let rulesArr = [];
         dataDable.map((item)=>{
           let a  = Object.values(item).every((oItem)=> !this.isEmpty(oItem))
            a && rulesArr.push(a)
         })
         let flag  = rulesArr.length === dataDable.length
        if (!flag) {
          this.$message.warning('请完善表格数据')
          return
        }
      }
      this.loading = true
      this.loadingBtn[status] = true
      let form = this.$clone(this.form)
      if (form.participant) {
        form.participant = this.form.participant.join()
      }
      let api = [updateTransferConstructionSurveyControlPoint, addTransferConstructionSurveyControlPoint][
        this.editModel - 1
      ]
      api(form)
        .then(() => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.updateControlPointHandover{
  @{deep} .ant-input-number-input{
    height: 29px;
  }
}
</style>
